package com.xnet.shiro.controller.authorize;

import com.xnet.common.annotation.SysLog;
import com.xnet.common.constant.SystemConstant;
import com.xnet.common.entity.AuthorizeMember;
import com.xnet.common.entity.R;
import com.xnet.common.entity.TreeEntity;
import com.xnet.common.entity.UserEntity;
import com.xnet.common.utils.BeanMapUtils;
import com.xnet.common.utils.JSONUtils;
import com.xnet.common.utils.TreeNodeUtils;
import com.xnet.shiro.entity.authorize.*;
import com.xnet.shiro.entity.base.DepartmentEntity;
import com.xnet.shiro.entity.base.OrganizeEntity;
import com.xnet.shiro.entity.base.RoleEntity;
import com.xnet.shiro.entity.base.UserRelationEntity;
import com.xnet.shiro.service.authorize.ModuleButtonService;
import com.xnet.shiro.service.authorize.ModuleColumnService;
import com.xnet.shiro.service.authorize.ModuleService;
import com.xnet.shiro.service.authorize.PermissionService;
import com.xnet.shiro.service.base.DepartmentService;
import com.xnet.shiro.service.base.OrganizeService;
import com.xnet.shiro.service.base.RoleService;
import com.xnet.shiro.service.base.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.apache.shiro.util.StringUtils.EMPTY_STRING;

/**
 * 用户权限设置
 *
 * @author xyc
 * @email
 * @url http://www.abcd.com
 * @date 2018年9月18日 下午3:37:36
 */
@RestController
@RequestMapping("/authorizeManage/permissionUserGroup")
public class PermissionUserGroupController {

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private ModuleButtonService moduleButtonService;

    @Autowired
    private ModuleColumnService moduleColumnService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private OrganizeService organizeService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    /**
     * 树形菜单列表
     *
     * @return
     */
    @RequestMapping("/moduleTree")
    public List<TreeEntity> moduleTree(String userGroupId) {

        List<AuthorizeEntity> existModule = permissionService.listModule(userGroupId);
        List<ModuleEntity> data = moduleService.listAllModule();
        List<TreeEntity> treeList = new ArrayList<>();
        for (ModuleEntity item : data) {
            TreeEntity tree = new TreeEntity();
            boolean hasChildren = data.stream().anyMatch(x -> x.getParentId().equals(item.getModuleId()));
            tree.setId(item.getModuleId());
            tree.setText(item.getFullName());
            tree.setValue(item.getModuleId());
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setHasChildren(hasChildren);
            tree.setParentId(item.getParentId());
            tree.setImg(item.getIcon());
            int checkState = existModule.stream().anyMatch(x -> x.getItemId().equals(item.getModuleId())) ? 1 : 0;
            tree.setCheckState(checkState);
            tree.setShowCheck(true);
            treeList.add(tree);
        }
        //创建结果列表
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(treeList, "0", newTreeList);
        return newTreeList;

    }

    /**
     * 树形菜单按钮列表
     *
     * @return
     */
    @RequestMapping("/moduleButtonTree")
    public List<TreeEntity> moduleButtonTree(String userGroupId) {

        List<AuthorizeEntity> existModuleButton = permissionService.listModuleButton(userGroupId);
        List<ModuleEntity> data = moduleService.listAllModule();
        List<TreeEntity> treeList = new ArrayList<>();
        for (ModuleEntity item : data) {
            TreeEntity tree = new TreeEntity();
            tree.setId(item.getModuleId());
            tree.setText(item.getFullName());
            tree.setValue(item.getModuleId());
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setHasChildren(true);
            tree.setParentId(item.getParentId());
            tree.setImg(item.getIcon());
            int checkState = existModuleButton.stream().anyMatch(x -> x.getItemId().equals(item.getModuleId())) ? 1 : 0;
            tree.setCheckState(checkState);
            tree.setShowCheck(true);
            treeList.add(tree);
        }

        List<ModuleButtonEntity> moduleButtonData = moduleButtonService.listAll();

        for (ModuleButtonEntity item : moduleButtonData) {
            TreeEntity tree = new TreeEntity();
            boolean hasChildren = moduleButtonData.stream().anyMatch(x -> x.getParentId().equals(item.getModuleButtonId()));
            tree.setId(item.getModuleButtonId());
            tree.setText(item.getFullName());
            tree.setValue(item.getModuleButtonId());
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setHasChildren(hasChildren);
            tree.setParentId(item.getParentId().equals("0") ? item.getModuleId() : item.getParentId());
            tree.setImg("fa fa-wrench " + item.getModuleId());
            int checkState = existModuleButton.stream().anyMatch(x -> x.getItemId().equals(item.getModuleButtonId())) ? 1 : 0;
            tree.setCheckState(checkState);
            tree.setShowCheck(true);
            treeList.add(tree);
        }

        //创建结果列表
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(treeList, "0", newTreeList);
        return newTreeList;

    }

    /**
     * 表格列列表
     *
     * @return
     */
    @RequestMapping("/moduleColumnTree")
    public List<TreeEntity> moduleColumnTree(String userGroupId) {

        List<AuthorizeEntity> existModuleButton = permissionService.listModuleColumn(userGroupId);
        List<ModuleEntity> data = moduleService.listAllModule();
        List<TreeEntity> treeList = new ArrayList<>();
        for (ModuleEntity item : data) {
            String moduleId = item.getModuleId();
            TreeEntity tree = new TreeEntity();
            tree.setId(moduleId);
            tree.setText(item.getFullName());
            tree.setValue(moduleId);
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setHasChildren(true);
            tree.setParentId(item.getParentId());
            tree.setImg(item.getIcon());
            int checkState = existModuleButton.stream().anyMatch(x -> x.getItemId().equals(moduleId)) ? 1 : 0;
            tree.setCheckState(checkState);
            tree.setShowCheck(true);
            treeList.add(tree);
        }
        List<ModuleColumnEntity> moduleColumnData = moduleColumnService.listAll();
        for (ModuleColumnEntity item : moduleColumnData) {
            TreeEntity tree = new TreeEntity();
            boolean hasChildren = moduleColumnData.stream().anyMatch(x -> x.getParentId().equals(item.getModuleColumnId()));
            tree.setId(item.getModuleColumnId());
            tree.setText(item.getFullName());
            tree.setValue(item.getModuleColumnId());
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setHasChildren(hasChildren);
            tree.setParentId(item.getParentId().equals("0") ? item.getModuleId() : item.getParentId());
            tree.setImg("fa fa-filter " + item.getModuleId());
            int checkState = existModuleButton.stream().anyMatch(x -> x.getItemId().equals(item.getModuleColumnId())) ? 1 : 0;
            tree.setCheckState(checkState);
            tree.setShowCheck(true);
            treeList.add(tree);
        }
        //创建结果列表
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(treeList, "0", newTreeList);
        return newTreeList;
    }

    /**
     * 数据权限
     *
     * @return
     */
    @RequestMapping("organizeTree")
    public Object organizeTree(String userGroupId) {

        List<AuthorizeDataEntity> existAuthorizeData = permissionService.listAuthorizeData(userGroupId);

        List<OrganizeEntity> organizeEntities = organizeService.list();

        List<DepartmentEntity> departmentEntities = departmentService.listAll();

        List<TreeEntity> treeList = new ArrayList<>();

        for (OrganizeEntity organizeEntity : organizeEntities) {
            TreeEntity tree = new TreeEntity();
            String organizeId = organizeEntity.getOrganizeId();
            String parentId = organizeEntity.getParentId();
            boolean hasChildren = organizeEntities.stream().anyMatch(x -> x.getParentId().equals(organizeId));
            if (!hasChildren) {
                hasChildren = departmentEntities.stream().anyMatch(x -> x.getOrganizeId().equals(organizeId));
                if (!hasChildren) continue;
            }
            tree.setHasChildren(hasChildren);
            tree.setId(organizeId);
            tree.setValue(organizeId);
            tree.setText(organizeEntity.getFullName());
            tree.setParentId(parentId);
            tree.setImg(parentId == "0" ? "fa fa-sitemap" : "fa fa-home");
            int checkState = existAuthorizeData.stream().anyMatch(x -> organizeId.equals(x.getResourceId())) ? 1 : 0;
            tree.setCheckState(checkState);
            tree.setShowCheck(true);
            tree.setIsExpand(true);
            tree.setComplete(true);
            treeList.add(tree);
        }

        for (DepartmentEntity departmentEntity : departmentEntities) {
            TreeEntity tree = new TreeEntity();
            String departmentId = departmentEntity.getDepartmentId();
            String parentId = departmentEntity.getParentId();
            boolean hasChildren = organizeEntities.stream().anyMatch(x -> x.getParentId().equals(departmentId));
            tree.setHasChildren(hasChildren);
            tree.setId(departmentId);
            tree.setValue(departmentId);
            tree.setText(departmentEntity.getFullName());
            tree.setParentId(parentId == "0" ? departmentEntity.getOrganizeId() : parentId);
            int checkState = existAuthorizeData.stream().anyMatch(x -> departmentId.equals(x.getResourceId())) ? 1 : 0;
            tree.setCheckState(checkState);
            tree.setShowCheck(true);
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setImg("fa fa-gears");
            treeList.add(tree);
        }
        int authorizeType = -1;
        if (!existAuthorizeData.isEmpty()) {
            authorizeType = existAuthorizeData.stream().findFirst().get().getAuthorizeType();
        }

        //创建结果列表
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(treeList, "0", newTreeList);
        //return newTreeList;

        JsonData jsonData = new JsonData();
        jsonData.setAuthorizeType(authorizeType);
        jsonData.setAuthorizeData(existAuthorizeData);
        jsonData.setTreeJson(JSONUtils.beanToJson(newTreeList, "yyyy-MM-dd"));
        return jsonData;

    }

    /**
     * 获取角色隶属的机构部门列表
     *
     * @return
     */
    @RequestMapping("/getDepartmentTree")
    public List<TreeEntity> getDepartmentTree(String userGroupId) {

        RoleEntity roleEntity = roleService.getRoleEntiyById(userGroupId);
        String organizeId = roleEntity.getOrganizeId();
        OrganizeEntity organizeEntity = organizeService.getOrganizeEnitiyById(organizeId);
        List<DepartmentEntity> departmentEntities = departmentService.listDepartment(organizeId, EMPTY_STRING);
        List<TreeEntity> treeList = new ArrayList<>();
        TreeEntity tree = new TreeEntity();
        tree.setId(organizeId);
        tree.setText(organizeEntity.getFullName());
        tree.setValue(organizeId);
        tree.setIsExpand(true);
        tree.setComplete(true);
        tree.setHasChildren(true);
        tree.setParentId("0");
        treeList.add(tree);

        for (DepartmentEntity item : departmentEntities) {
            tree = new TreeEntity();
            String departmentId = item.getDepartmentId();
            boolean hasChildren = departmentEntities.stream().anyMatch(x -> x.getParentId().equals(departmentId));
            tree.setHasChildren(hasChildren);
            tree.setId(departmentId);
            tree.setText(item.getFullName());
            tree.setValue(departmentId);
            tree.setParentId(item.getParentId().equals("0") ? roleEntity.getOrganizeId() : item.getParentId());
            tree.setIsExpand(true);
            tree.setComplete(true);
            treeList.add(tree);
        }
        //创建结果列表
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(treeList, "0", newTreeList);
        return newTreeList;
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @RequestMapping("/getUserList")
    public Object getUserList(String userGroupId) {

        List<UserRelationEntity> userRelationEntities = permissionService.listMember(userGroupId);
        List<UserEntity> userEntities = userService.listAllUser();
        List<AuthorizeMember> memberDataList = new ArrayList();
        for (UserEntity user : userEntities) {
            AuthorizeMember item = new AuthorizeMember();
            BeanMapUtils.mapToBean(BeanMapUtils.beanToMap(user), item);
            String userId = item.getUserId();
            boolean isCheck = userRelationEntities.stream().anyMatch(x -> x.getUserId().equals(userId));
            item.setIsCheck(isCheck ? 1 : 0);
            if (isCheck) {
                Integer isDefault = userRelationEntities.stream().filter(x -> x.getUserId().equals(userId)).findFirst().get().getIsDefault();
                item.setIsDefault(isDefault);
            } else {
                item.setIsDefault(0);
            }
            memberDataList.add(item);
        }
        return memberDataList;
    }


    /**
     * 保存权限
     *
     * @param map
     * @return
     */
    @SysLog("保存用户组权限")
    @RequestMapping("/saveAuthorize")
    public R saveAuthorize(@RequestBody Map<String, Object> map) {
        String userGroupId = map.get("userGroupId").toString();
        String moduleIds = map.get("moduleIds").toString();
        String moduleButtonIds = map.get("moduleButtonIds").toString();
        String moduleColumnIds = map.get("moduleColumnIds").toString();
        String authorizeDataJson = map.get("authorizeDataJson").toString();
        String[] arrayModuleId = moduleIds.split(",");
        String[] arrayModuleButtonId = moduleButtonIds.split(",");
        String[] arrayModuleColumnId = moduleColumnIds.split(",");
        List<AuthorizeDataEntity> authorizeDataEntities = (List<AuthorizeDataEntity>) JSONUtils.jsonToArray(authorizeDataJson, AuthorizeDataEntity.class);
        return permissionService.saveAuthorize(SystemConstant.AuthorizeCategoryEnum.UserGroup, userGroupId, arrayModuleId, arrayModuleButtonId, arrayModuleColumnId, authorizeDataEntities);
    }

    /**
     * 保存角色成员
     *
     * @param map
     * @return
     */
    @SysLog("保存角色成员")
    @RequestMapping("/saveMember")
    public R saveMember(@RequestBody Map<String, Object> map) {
        String userGroupId = map.get("userGroupId").toString();
        String userIds = map.get("userIds").toString();
        return permissionService.saveMember(SystemConstant.AuthorizeCategoryEnum.UserGroup, userGroupId,userIds);
    }


    class JsonData {

        private int authorizeType;

        private List<AuthorizeDataEntity> authorizeData;

        private String treeJson;

        public int getAuthorizeType() {

            return authorizeType;
        }

        public void setAuthorizeType(int authorizeType) {

            this.authorizeType = authorizeType;
        }

        public List<AuthorizeDataEntity> getAuthorizeData() {

            return authorizeData;
        }

        public void setAuthorizeData(List<AuthorizeDataEntity> authorizeData) {

            this.authorizeData = authorizeData;
        }

        public String getTreeJson() {

            return treeJson;
        }

        public void setTreeJson(String treeJson) {

            this.treeJson = treeJson;
        }
    }

}
